package HttpThread;

import Dispatch.DispatcherService;
import HttpBean.Request.Request;
import HttpBean.Request.RequestImpl.RequestGetStringImpl;
import HttpBean.Request.RequestImpl.RequestPostStringImpl;
import HttpBean.Request.RequestLine;
import HttpBean.Response.Response;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.Arrays;

public class HttpServerHandle extends ChannelHandlerAdapter {
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] req = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(req);
        String[] body = new String(req,"UTF-8").split("\r\n");
        Request request = null;
        RequestLine requestLine = new RequestLine(body[0]);
        if (requestLine.getMethod().equals("GET")){
            request = new RequestGetStringImpl(Arrays.copyOfRange(body, 1, body.length),requestLine);
        }else if(requestLine.getMethod().equals("POST")){
            request = new RequestPostStringImpl(Arrays.copyOfRange(body, 1, body.length),requestLine);
        }
        System.out.println(request.toString());
        Response response = DispatcherService.doDispatch(request);
        ByteBuf resp = Unpooled.copiedBuffer(response.getResponse().getBytes());
        ctx.writeAndFlush(resp);
        ctx.close();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
}
